package net.oschina.simpleplus.aop;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.oschina.simpleplus.cnf.jwt.JwtCnf;
import net.oschina.simpleplus.vo.UserVo;

@Aspect
@Component
public class RestAspect {
	@Autowired
	private JwtCnf jwtCnf;

	@Pointcut("execution(* net.oschina.simpleplus.ctrl.*.*(..)) and @annotation(org.springframework.web.bind.annotation.RestController)")
	public void rest(){
		
	}
	
	@Around("rest()")
	public Object process(ProceedingJoinPoint pjp)throws Throwable{
		Object[] args = pjp.getArgs();
		if(!((MethodSignature)pjp.getSignature()).getMethod().isAnnotationPresent(SkipJwtAuth.class)){
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
		            .getRequest();
			UserVo userVo = jwtCnf.parserJwt(request.getHeader("token"));
			args[0] = userVo;
		}
		Map<String, Object> m = null;
		try{
			m = (Map<String, Object>) pjp.proceed(args);
			m.put("code", 2);
		}catch (Exception e) {
			m = new HashMap<>();
			m.put("code", 4000);
			m.put("msg", e.getMessage());
		}
		return m;
	}
}
